var React = require('react');

var todoItem = React.createClass({
	getInitialState:function(){
		return{
			isModify:false
		}
	},
	changeState:function(e){
		this.props.todo.complete=!this.props.todo.complete;
		this.props.modifyTodo(this.props.todo);
	},
	deleteItem:function(){
		this.props.deleteById(this.props.todo.id);
	},
	changeTxt:function(){
		this.setState({
			isModify:true
		})
	},
	keyUp:function(e){
		if(e.nativeEvent.keyCode==13){
			var newTxt=this.refs.newTxt.value;
			if(!newTxt)
			{
				alert("傻啊，这能为空吗");
				return false;
			}
			else if(this.props.todo.txt!=newTxt)
			{
				this.props.todo.txt=newTxt;
				this.props.modifyTodo(this.props.todo);
			}			
			this.setState({
				isModify:false
			})
		}
		else if(e.nativeEvent.keyCode==27)
		{
			this.setState({
				isModify:false
			})
		}
	},
  	render: function () {
  		var todo=this.props.todo;
		return(
				<li key={todo.id} className={todo.complete?'todo complete':'todo'}>
				<div className="view" style={this.state.isModify?{display:'none'}:{display:'block'}}>
					<input ref="aaa" type="checkbox" defaultChecked={todo.complete} value={'ck'+todo.id} onClick={this.changeState} />
					<label onDoubleClick={this.changeTxt}>{todo.txt}</label>
					<button onClick={this.deleteItem} className="destory">&times;</button>
				</div>
				<input type="text" className="edit" 
					ref="newTxt"
					style={this.state.isModify?{display:'block'}:{display:'none'}} 
					defaultValue={todo.txt} 
					onKeyUp={this.keyUp}	/>
			</li>
		)
  		
	  }
});

module.exports = todoItem;